<?php
/**
 *
 *
 * @date    2018-07-23 17:17:02
 * @version $Id$
 */

namespace App\Commons\Services;

use Carbon\Carbon;
use Sts\AssumeRoleRequest;
use Sts\Core\DefaultAcsClient;
use Sts\Core\Profile\DefaultProfile;
use DateTimeZone;

class AliyunStsClient
{
    private $client;
    private $request;

    public function __construct()
    {
        $config = config('aliyun_sts');
        $iClientProfile = DefaultProfile::getProfile($config['region'], $config['key'], $config['secret']);
        $this->client = new DefaultAcsClient($iClientProfile);

        $this->request = new AssumeRoleRequest();

        $this->request->setRoleSessionName("external-username");
        $this->request->setRoleArn($config['role_arn']);
        $this->request->setPolicy(json_encode($config['policy']));
        $this->request->setDurationSeconds($config['expire_time']);
    }

    public function getTokenInfo()
    {
        $response = $this->client->doAction($this->request);

        $result = array();
        $body = $response->getBody();
        $content = json_decode($body);

        // $result['status'] = $response->getStatus();
        if ($response->isSuccess()) {
            $expiration = Carbon::parse($content->Credentials->Expiration);
            $expiration->timezone(config('app.timezone'));
            $result['AccessKeyId'] = $content->Credentials->AccessKeyId;
            $result['AccessKeySecret'] = $content->Credentials->AccessKeySecret;
            $result['Expiration'] = $expiration->format('Y-m-d H:i:s');
            $result['SecurityToken'] = $content->Credentials->SecurityToken;
        } else {
            sentry('获取aliyun sts授权失败，status_code:'. $response->getStatus(), ['body' => $body]);
            throw_e('获取aliyun sts授权失败，status_code:'. $response->getStatus());
        }

        return $result;
    }

    public function __call(string $method, array $arguments)
    {
        if (method_exists($this->request, $method)) {
            $this->request->{$method}(...$arguments);
        } else {
            throw_e(new \BadMethodCallException);
        }
        return $this;
    }
}
